/**
 * C Implementation: grib_set_data
 *
 * Description: set the data contained in a GRIB file.
 *              In this example no missing values are present
 *              If there are missing values, refer to: grib_set_bitmap
 * 
 * 设置包含在 GRIB 文件中的数据。
 * 在这个例子中不存在缺失值，
 * 如果有缺失值，参考：grib_set_bitmap
 *
 */
#include <stdio.h>
#include <stdlib.h>
#include "eccodes.h"

static void usage(const char* prog)
{
    printf("usage: %s out.grib\n", prog);
    exit(1);
}

int sfx_grib_set_data()
{
    int err = 0;

    // Sample files (样本文件) are stored in the samples directory (use codes_info to
    // see where that is).  The default sample path can be changed by
    // setting the environment variable ECCODES_SAMPLES_PATH

    // Note: the full name of the sample file is "regular_ll_pl_grib1.tmpl"
    const char* sample_filename = "regular_ll_pl_grib1";

    // Here is how you can get the samples path
    const char* samples_path = codes_samples_path(NULL);
    printf("Using samples path: %s\n", samples_path);

    // create new handle from message in sample file
    codes_handle* h = codes_grib_handle_new_from_samples(0, sample_filename);
    if (h == NULL) {
        fprintf(stderr, "Error: unable to create handle from sample file %s\n", sample_filename);
        exit(1);
    }

    // 这里我们只更改数据值, 因此值的数量将与示例 GRIB 相同。
    // But if your data array has a different size, then specify (指定) the grid geometry
    // (e.g. keys Ni, Nj etc) and set the correct number of data values
    size_t values_len = 0;
    CODES_CHECK(codes_get_size(h, "values", &values_len), 0);
    double* values = (double*)malloc(values_len * sizeof(double));

    double d   = 10e-8;
    double e   = d;
    long count = 1;
    for (int i = 0; i < values_len; i++) {
        // 
        if (count > 100) {
            e *= 10;
            count = 1;
        }
        values[i] = d;
        printf("%g \n",values[i]);
        d += e;
        count++;
    }

    // 设置数据精度 (值的位数)
    CODES_CHECK(codes_set_long(h, "bitsPerValue", 16), 0);

    // set data values 
    CODES_CHECK(codes_set_double_array(h, "values", values, values_len), 0);

    // 把消息写入文件
    char* outfile = "d:/temp/out.grib";
    CODES_CHECK(codes_write_message(h, outfile, "w"), 0);

    // free memory
    free(values);
    codes_handle_delete(h);
    return 0;
}
